package cn.org.donald.framework.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Get bean from spring ioc container
 * @author ： Donald
 * @since ： 2020/10/17 17:21
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    /**
     * Get a bean from spring by bean name.
     * @param beanName bean name
     * @return An object
     */
    public static Object getBean(String beanName){
        return applicationContext.getBean(beanName);
    }

    public static void printAllBeans(){
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
    }

}
